package com.anrongtec.zcpt.logo;

import android.animation.ArgbEvaluator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.manager.AppDownManagerActivity;
import com.anrongtec.zcpt.manager.AppStateManager;
import com.anrongtec.zcpt.manager.BadgeViewManager;
import com.anrongtec.zcpt.manager.CheckNewVersionManager;
import com.anrongtec.zcpt.openapi.util.ToastShow;
import com.anrongtec.zcpt.receiver.APPDownloadReceiver;
import com.anrongtec.zcpt.receiver.APPUpgradeReceiver;
import com.anrongtec.zcpt.service.AppUpgradeService;
import com.anrongtec.zcpt.tab01.TabFirstFragment;
import com.anrongtec.zcpt.tab02.TabSecondNewFragment;
import com.anrongtec.zcpt.tab03.TabThirdFragment;
import com.anrongtec.zcpt.tab04.TabFourthFragment;
import com.anrongtec.zcpt.ui.SearchActivity;
import com.ashokvarma.bottomnavigation.BadgeItem;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationBar.OnTabSelectedListener;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;

public class MainActivity extends BaseActivity implements OnTabSelectedListener, OnClickListener {

	private Toolbar toolBar;
	private EditText et_toolbar;
	private ImageView iv_toolbar;
	private ImageView iv_down;
	private TabFirstFragment tab01;
//	private TabMainFragment tab01;
	private TabSecondNewFragment tab02;
	private TabThirdFragment tab03;
	private TabFourthFragment tab04;
	private static final String TAB01 = "tab01", TAB02 = "tab02", TAB04 = "tab04";
	private LinearLayout linearLayout;
	private BottomNavigationBar bottomBar;
	private BottomNavigationItem item01, item02, item03, item04;
	private int color0, color1, color2, color3, currentColor;
	private ArgbEvaluator evaluator;

	private int index = 0;
	private APPUpgradeReceiver upgradeReceiver;
	private APPDownloadReceiver downloadReceiver;
	private BroadcastReceiver exitReceiver;

	private Intent intent, service;

	/** bottomBar个人页面tab 红点 */
	private BadgeItem badgeItem;

	/** 正在下载的数量, 需要更新的数量 */
	private int downloadCount, upgradeCount;

	// **************dialog view**************
	private ProgressBar bar;
	// 已下载大小, 总大小
	private TextView tv_size, tv_total;
	private AppStateManager manager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleShow(false);
		setContentView(R.layout.activity_main);

		initViews();

		initColors();

		initToolBar();

		initBottomBar();

		initFragment(0);

		//强制更新
		CheckNewVersionManager.getInstance().checkVersion(MainActivity.this,false);

		// 打开检测app是否需要更新的service
		service = new Intent(this, AppUpgradeService.class);
		startService(service);
		registReceiver();
		registerAppStatus();
	}

	/**
	 * TODO 注册广播接收器
	 */
	private void registerAppStatus() {
		manager = new AppStateManager(MainActivity.this);
		manager.begin(new AppStateManager.AppStateListener() {

			@Override
			public void onAppUninstalled(String pkgName) {
				tab01.refresh();
				Log.e("tab01","卸载");
				if (tab02 != null) {
					tab02.refresh();
				}
			}

			@Override
			public void onAppRelpaced(String pkgName) {
				tab01.refresh();
				Log.e("tab02","更新");
				if (tab02 != null) {
					tab02.refresh();
				}
			}

			@Override
			public void onAppInstalled(String pkgName) {
				tab01.refresh();
				Log.e("tab03","安装");
				if (tab02 != null) {
					tab02.refresh();
				}
			}
		}, true);
	}

	private void registReceiver() {
		// // **************app安装卸载 广播接收器****************
		// IntentFilter filter = new IntentFilter();
		// filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		// filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
		// filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		// filter.addDataScheme("package");
		// receiver = new APPReceiver() {
		// @Override
		// public void receive(Context context, Intent intent, String
		// packageName) {
		// tab01.refresh();
		// if (tab02 != null) {
		// tab02.refresh();
		// }
		// }
		// };
		// registerReceiver(receiver, filter);

		// **********************app有更新 广播接收器********************
		IntentFilter filter1 = new IntentFilter();
		filter1.addAction(Constant.Action.APP_UPGRADE);
		upgradeReceiver = new APPUpgradeReceiver() {
			@Override
			public void receive(Context context, Intent intent) {
				// 需要更新的app
				// ArrayList<AppModel> checkResut = (ArrayList<AppModel>)
				// intent.getSerializableExtra(Constant.DATA_APP_UPGRADE);
				showUpgradeBadge();
			}
		};
		registerReceiver(upgradeReceiver, filter1);

		// **********************app开始下载 广播接收器********************
		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(Constant.Action.APP_DOWNLOAD);
		downloadReceiver = new APPDownloadReceiver() {
			@Override
			public void receive(Context context, Intent intent) {
				showDownloadingBadge();
			}
		};
		registerReceiver(downloadReceiver, filter2);

		// ***************************退出*******************************
		IntentFilter filter3 = new IntentFilter();
		filter3.addAction(Constant.Action.EXIT);
		exitReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				finish();
			}
		};
		registerReceiver(exitReceiver, filter3);
	}

	@Override
	protected void onResume() {
		showUpgradeBadge();
		showDownloadingBadge();
		super.onResume();
	}

	/**
	 * 显示主页面bottom和tab04 页面的【需要更新】 红点
	 */
	private void showUpgradeBadge() {
		upgradeCount = AppUpgradeService.getNeedUpgreade().size();
		downloadCount = APPDownloadManager.getDownloadTaskCount();
		showBadge();
	}

	/**
	 * 显示toolbar 下载的红点
	 */
	private void showDownloadingBadge() {
		downloadCount = APPDownloadManager.getDownloadTaskCount();
		// toolbar下载的红点
		BadgeViewManager.getInstance(this).setBadge(iv_toolbar, downloadCount);
		showBadge();
	}

	private void showBadge() {
		// main bottom红点
		if (upgradeCount + downloadCount == 0) {
			badgeItem.hide();
		} else {
			badgeItem.setText(upgradeCount + downloadCount + "");
			badgeItem.show();
		}

		// tab04 页面红点刷新
		if (tab04 != null) {
			tab04.setBadge();
		}
	}

	@Override
	protected void onDestroy() {
		if (upgradeReceiver != null) {
			unregisterReceiver(upgradeReceiver);
		}
		if (downloadReceiver != null) {
			unregisterReceiver(downloadReceiver);
		}
		if (exitReceiver != null) {
			unregisterReceiver(exitReceiver);
		}
		manager.unregisterListener();
		stopService(service);
		// unbindService();
		super.onDestroy();
	}

	private long exitTime = 0;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void exit() {
		if(System.currentTimeMillis() - exitTime >2000) {
			ToastShow.makeToast(MainActivity.this,"再按一次退出移动警务!");
			exitTime = System.currentTimeMillis();
		} else {
			finish();
			System.exit(0);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Constant.POSITION, index);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			index = savedInstanceState.getInt(Constant.POSITION);
			if (index != -1) {
				initFragment(index);
			}
		}
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void initViews() {
		linearLayout = (LinearLayout) findViewById(R.id.linearlayout_main);
		et_toolbar = (EditText) findViewById(R.id.et_toolbar_search);
		et_toolbar.setFocusable(false);
		et_toolbar.setOnClickListener(this);

		iv_down = (ImageView) findViewById(R.id.iv_toolbar);
		iv_down.setOnClickListener(this);

	}

	/**
	 * 初始化fragment
	 */
	private void initFragment(int position) {
		// fragment引用为null，但是内存中对象依然存在。
		// 只判断fragment会导致重复的fragment被创建导致页面叠层，所以通过tag找回之前的引用。 如果找回仍为null，则重新new
		FragmentManager fm = getSupportFragmentManager();
		tab01 = (TabFirstFragment) fm.findFragmentByTag(TAB01);
//		tab01 = (TabMainFragment) fm.findFragmentByTag(TAB01);
		tab02 = (TabSecondNewFragment) fm.findFragmentByTag(TAB02);
		tab04 = (TabFourthFragment) fm.findFragmentByTag(TAB04);

		refreshFragment(position);
	}

	/**
	 * 更新显示fragment
	 * 
	 * @param position
	 */
	private void refreshFragment(int position) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		index = position;

		hideFragment(transaction);

		switch (position) {
		case 0:
			if (tab01 == null) {
				tab01 = new TabFirstFragment();
//				tab01 = new TabMainFragment();
				transaction.add(R.id.main_fragment, tab01, TAB01);
			} else {
				transaction.show(tab01);
			}
			linearLayout.setVisibility(View.VISIBLE);
			toolBar.setVisibility(View.GONE);
			break;
//			if (tabMain == null) {
//				tabMain = new TabFirstFragment();
//				transaction.add(R.id.main_fragment, tabMain, TAB01);
//			} else {
//				transaction.show(tabMain);
//			}
//			linearLayout.setVisibility(View.VISIBLE);
//			break;

		case 1:
			if (tab02 == null) {
				tab02 = new TabSecondNewFragment();
				transaction.add(R.id.main_fragment, tab02, TAB02);
			} else {
				transaction.show(tab02);
			}
			linearLayout.setVisibility(View.VISIBLE);
			toolBar.setVisibility(View.VISIBLE);
			break;

		case 2:
			if (tab04 == null) {
				tab04 = new TabFourthFragment();
				transaction.add(R.id.main_fragment_out, tab04, TAB04);
			} else {
				transaction.show(tab04);
			}
			break;
		}

		transaction.commit();
	}

	/**
	 * 隐藏fragment
	 * 
	 * @param transaction
	 */
	private void hideFragment(FragmentTransaction transaction) {
		if (tab01 != null) {
			transaction.hide(tab01);
		}
//		if (tabMain != null) {
//			transaction.hide(tabMain);
//		}
		if (tab02 != null) {
			transaction.hide(tab02);
		}
		if (tab03 != null) {
			transaction.hide(tab03);
		}
		if (tab04 != null) {
			transaction.hide(tab04);
		}

		linearLayout.setVisibility(View.INVISIBLE);
	}

	/**
	 * 获取显示的颜色
	 */
	private void initColors() {
		// 颜色
		color0 = ContextCompat.getColor(this, R.color.colorPrimary_blue);
		color1 = ContextCompat.getColor(this, android.R.color.holo_red_light);
		color2 = ContextCompat.getColor(this, android.R.color.holo_green_light);
		color3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
		evaluator = new ArgbEvaluator();
	}

	/**
	 * 设置toolbar
	 */
	private void initToolBar() {
		// toolbar
		toolBar = (Toolbar) findViewById(R.id.toolbar);
		toolBar.setTitle("测试tablayout和viewpager");
		iv_toolbar = (ImageView) findViewById(R.id.iv_toolbar);
		setSupportActionBar(toolBar);
		getSupportActionBar().setHomeButtonEnabled(false); // 这个小于4.0版本的默认值为true的。但是在4.0及其以上是false，该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。
															// true 图标可以点击 false
															// 不可以点击。
		getSupportActionBar().setDisplayHomeAsUpEnabled(false); // 给左上角图标的左边加上一个返回的图标
																// 。对应ActionBar.DISPLAY_HOME_AS_UP
		// getSupportActionBar().setDisplayShowHomeEnabled(true);
		// //使左上角图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标，对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
		// getSupportActionBar().setDisplayShowCustomEnabled(true); //
		// 使自定义的普通View能在title栏显示，即actionBar.setCustomView能起作用，对应ActionBar.DISPLAY_SHOW_CUSTOM

	}

	/**
	 * 初始化底部导航栏
	 */
	private void initBottomBar() {
		bottomBar = (BottomNavigationBar) findViewById(R.id.main_bottom_bar);

		item01 = new BottomNavigationItem(R.drawable.icon_bottom_01, "首页");
		// item01.setBadgeItem(new
		// BadgeItem().setText("1").setHideOnSelect(true).show());
		item02 = new BottomNavigationItem(R.drawable.icon_bottom_02, "应用");
		// item03 = new BottomNavigationItem(R.drawable.icon_bottom_03, "分类");
		item04 = new BottomNavigationItem(R.drawable.icon_bottom_04, "个人");
		badgeItem = new BadgeItem().hide();
		item04.setBadgeItem(badgeItem);
		bottomBar.setMode(BottomNavigationBar.MODE_FIXED);
		bottomBar.addItem(item01).addItem(item02)
				// .addItem(item03)
				.addItem(item04).initialise();
		bottomBar.setTabSelectedListener(this);
	}

	@Override
	public void onTabSelected(int position) {
		initFragment(position);
	}

	@Override
	public void onTabUnselected(int position) {

	}

	@Override
	public void onTabReselected(int position) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_toolbar_search:
			startActivity(SearchActivity.class);
			break;

		case R.id.iv_toolbar:
			startActivity(AppDownManagerActivity.class);
			break;
		}
	}

	// public void bindService() {
	// Util.post(new Runnable() {
	//
	// @Override
	// public void run() {
	// // 创建所需绑定服务的Intent
	// intent = new Intent("com.anrongtec.getuaInfo");
	// intent.setPackage("com.anrongtec.ua");
	// isBind = bindService(intent, conn, Service.BIND_AUTO_CREATE);
	// LogUtil.trace(Log.DEBUG, "UA", "统一认证:" + isBind);
	// // 不是专用手机无法绑定服务, isBind就是false
	// // if (!isBind) {
	// // }
	// }
	// });
	// }

	/**
	 * 这是当用户身份更变的时候做的操作，应该重新登录及验证
	 */
	// private OnStaffChangeInterface mCallback = new
	// OnStaffChangeInterface.Stub() {
	//
	// @Override
	// public void onStaffChanged(Staff staff) throws RemoteException {
	// LogUtil.trace(Log.DEBUG, "UA", "统一认证服务onStaffChanged");
	// Util.post(MainActivity.this, new Runnable() {
	//
	// @Override
	// public void run() {
	// // showMyDialog();
	// intent = new Intent(Constant.Action.STAFF_CHANGED);
	// sendBroadcast(intent);
	// }
	// });
	// }
	// };

	/**
	 * 统一认证服务
	 */
	// private ServiceConnection conn = new ServiceConnection() {
	// @Override
	// public void onServiceConnected(ComponentName name, IBinder service) {
	// LogUtil.trace(Log.DEBUG, "UA", "统一认证服务连接成功");
	// getInfoInterface = GetInfoInterface.Stub.asInterface(service);
	// try {
	// getInfoInterface.registerStaffChangeCallback(mCallback);
	// } catch (RemoteException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// @Override
	// public void onServiceDisconnected(ComponentName name) {
	// LogUtil.trace(Log.DEBUG, "UA", "统一认证服务onServiceDisconnected");
	// if (getInfoInterface != null) {
	// try {
	// getInfoInterface.unregisterStaffChangeCallback(mCallback);
	// } catch (RemoteException e) {
	// e.printStackTrace();
	// }
	// getInfoInterface = null;
	// }
	// }
	// };

	/**
	 * 解绑服务
	 */
	// public void unbindService() {
	// LogUtil.trace(Log.DEBUG, "UA", "统一认证服务解绑");
	// try {
	// unbindService(conn);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }




}
